package gdingtalk

import (
	"context"
	"errors"
	"github.com/beego/beego/v2/client/cache"
	_ "github.com/beego/beego/v2/client/cache/redis"
	"github.com/beego/beego/v2/core/logs"
	"time"
)

var gCache *Cache

func initCache(cacheConn string) error {
	c, err := newCache("redis", cacheConn)
	gCache = &c
	return err
}

type Cache struct {
	beegoCache cache.Cache
}

// NewCache 实例化
func newCache(cacheType string, cacheConn string) (Cache, error) {
	_cache, err := cache.NewCache(cacheType, cacheConn)
	if err != nil {
		logs.Error("cache init err: %s", err)
		return Cache{}, err
	}
	return Cache{
		beegoCache: _cache,
	}, nil
}

// GetCache 返回缓存句柄
func (__ *Cache) getCache() cache.Cache {
	return __.beegoCache
}

// cGet 获取缓存信息，如果不存在返回空字符串
func cGet(key string) (string, error) { return gCache.cGet(key) }
func (__ *Cache) cGet(key string) (string, error) {
	value, err := __.getCache().Get(context.Background(), key)
	if err != nil {
		return "", err
	}
	if value == nil {
		return "", errors.New("value is empty")
	}
	switch value.(type) {
	case []byte:
		return string(value.([]byte)), nil
	case string:
		return value.(string), nil
	default:
		return "", nil
	}
}

// cPut 更新缓存信息，如果不存在返回空字符串
func cPut(key, value string, expireSecond int64) error { return gCache.cPut(key, value, expireSecond) }
func (__ *Cache) cPut(key, value string, expireSecond int64) error {
	err := __.getCache().Put(context.Background(), key, value, time.Duration(expireSecond)*time.Second)
	return err
}

// cDel 删除缓存信息
func cDel(key string) error { return gCache.cDel(key) }
func (__ *Cache) cDel(key string) error {
	err := __.getCache().Delete(context.Background(), key)
	return err
}
